import socket
import time
import json
import subprocess
# from pachong import scrape_data_and_save_to_file

# 调用函数来执行代码并获取返回值
#api_address = scrape_data_and_save_to_file()
# print(f"获取到的 API 地址为: {api_address}")

# 定义多个数据字段
temp = "33"
humi = "60"
led = "on"
# 构建 HTTP 响应的数据部分
data_dict = {
    "Temp": temp,
    "Humi": humi,
    "LED": led
}
# # 将数据字段拼接成一个字符串
# data_string = "\r\n".join(data_fields)

# 将字典转换成 JSON 格式的字符串
json_data = json.dumps(data_dict)
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 监听的IP和端口
server_socket.bind(('127.0.0.1', 550))
server_socket.listen(5)

while True:
    # 接受客户端连接
    client_socket, address = server_socket.accept()
    print(f'连接来自：{address}')

    # 接收数据
    data = client_socket.recv(1024).decode()
    print(f'接收到的数据：{data}')

    # 处理接收到的数据
    if 'id=01' in data:
        response_data = f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{json_data}"
        client_socket.send(response_data.encode())
        print(f'发送的数据：{response_data}')

    # 关闭连接
    client_socket.close()